<?php

defined('BASEPATH') or die('forbidden');

class Role_Controller Extends Controller {

    function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
    }

    function index() {
        $this->view->display("role/role/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $rows = array();
        $rolenums = array();
        $roledata = get_role_data('5c7ace4a-b3bf-4734-9afd-6bda7ed9b964');
        if ($this->auth->fields['role_rank'] < 100) {
            $role = get_role_data($this->auth->fields['role_id']);
            $ids = array(0);
            foreach ($role as $m => $n) {
                $ids[] = $n['id'];
            }
            $where .= " AND ID IN ('" . (implode("','", $ids)) . "')";
        }
        $sql = "SELECT COUNT(*) AS num FROM {pre}role r WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $this->db->query("SELECT {$colsinfo} FROM {pre}role r WHERE {$where}
                ORDER BY `{$sortname}` {$sortorder} 
                LIMIT {$offset},{$rp}");
        while ($n = $this->db->get_array('default', MYSQL_NUM)) {
            $n[3] = isset($roledata[$n[3]]) ? $roledata[$n[3]]['name'] : "无";
            get_datetime(array(&$n[4], &$n[5]), false);
            $rows[] = array('id' => $n[0], 'cell' => array_values($n));
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    function add() {
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $row = $this->db->one("SELECT * FROM {pre}role WHERE name='{$rowdata['name']}'");
            if (is_array($row))
                error(translate('ROLE_ROLE_NAME_EXISTED', $rowdata['name']));
            if ($this->auth->fields['role_rank'] < 100) {
                $roleinfo = $this->auth->get_role($rowdata['father_id']);
                if (!$roleinfo || $roleinfo['rank'] >= $this->auth->fields['role_rank'])
                    $rowdata['father_id'] = $this->auth->fields['role_id'];
            }
            if ($rowdata['rank'] > $this->auth->fields['role_rank']) {
                error(translate('ROLE_ROLE_RANK_TOO_BIG'));
            }
            $allow_uri = explode("\r\n", $rowdata['allow_uri']);
            $deny_uri = explode("\r\n", $rowdata['deny_uri']);
            unset($rowdata['allow_uri'], $rowdata['deny_uri']);
            $rowdata['permission'] = serialize(array('allow_uri' => $allow_uri, 'deny_uri' => $deny_uri, 'admin' => $rowdata['permission']));
            $rowdata['createtime'] = $rowdata['modifytime'] = time();
            $rowdata['id'] = get_uuid();
            $this->db->insert('{pre}role', $rowdata, true);
            insert_log(translate('ROLE_ROLE_LOG_ADD', $rowdata['name']));
            $this->auth->set_role_data();
            cp_tips('success', $rowdata['id']);
        }
        $roledata = array();
        $roledata[$this->auth->fields['role_id']] = $this->auth->fields['role_name'];
        $role = get_role_data($this->auth->fields['role_id']);
        foreach ($role as $value) {
            $roledata["{$value['id']}"] = $value['name'];
        }
        $rolelist = $this->form->select('row[father_id]', $roledata);
        $this->view->assign("rolelist", $rolelist);
        $this->view->display("role/role/add");
    }

    function edit($id) {
        if (!$id)
            error(translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}role WHERE id='{$id}'");
        if (!is_array($row))
            error(translate('C_INVALID_PARAM_ID', $id));
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $one = $this->db->one("SELECT * FROM {pre}role WHERE name='{$rowdata['name']}' AND id!='{$id}'");
            if (is_array($one))
                error(translate('ROLE_ROLE_NAME_EXISTED', $rowdata['name']));
            if ($this->auth->fields['role_rank'] < 100) {
                $roleinfo = $this->auth->get_role($rowdata['father_id']);
                if ($roleinfo && in_array($rowdata['father_id'], get_role_childen_ids($row['id']))) {
                    error(translate('ROLE_ROLE_RANK_CONFLICT'));
                }
                if (!$roleinfo || $roleinfo['rank'] >= $this->auth->fields['role_rank'])
                    $rowdata['father_id'] = $this->auth->fields['role_id'];
            }
            if ($rowdata['rank'] > $this->auth->fields['role_rank']) {
                error(translate('ROLE_ROLE_RANK_TOO_BIG'));
            }
            $allow_uri = explode("\r\n", $rowdata['allow_uri']);
            $deny_uri = explode("\r\n", $rowdata['deny_uri']);
            unset($rowdata['allow_uri'], $rowdata['deny_uri']);
            $rowdata['permission'] = serialize(array('allow_uri' => $allow_uri, 'deny_uri' => $deny_uri, 'admin' => $rowdata['permission']));
            $rowdata['modifytime'] = time();
            $result = $this->db->update('{pre}role', $rowdata, array('id' => $id));
            if ($result) {
                $rowdata['id'] = $row['id'];
                insert_log(translate('ROLE_ROLE_LOG_EDIT', $rowdata['name']));
                $this->auth->set_role_data();
                cp_tips('success', $id);
            } else {
                error('');
            }
        }
        $roledata = array();
        $roledata[$this->auth->fields['role_id']] = $this->auth->fields['role_name'];
        $role = get_role_data($this->auth->fields['role_id']);
        foreach ($role as $value) {
            if ($value['id'] == $row['id'])
                continue;
            $roledata["{$value['id']}"] = $value['name'];
        }
        $row['rolelist'] = $this->form->select('row[father_id]', $roledata, $row['father_id']);
        $permission = unserialize($row['permission']);
        $row['allow_uri'] = implode("\r\n", $permission['allow_uri']);
        $row['deny_uri'] = implode("\r\n", $permission['deny_uri']);
        $row['admin'] = $permission['admin'];
        $this->view->display("role/role/edit", array('row' => $row));
    }

    function del($id) {
        $c = 0;
        $r = '';
        if ($id === 0)
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        $row = $this->db->one("SELECT * FROM {pre}role WHERE id='{$id}'");
        if (!is_array($row))
            json_output($c, translate('C_INVALID_PARAM_ID', $id));
        if ($row['rank'] == 100)
            json_output($c, translate('ROLE_ROLE_SUPER_ADMIN_COULD_NOT_DEL'));
        if ($row['rank'] > $this->auth->fields['role_rank'])
            json_output($c, translate('C_INSUFFICIENT_PERMISSIONS'));
        $num1 = $this->db->one("SELECT COUNT(*) AS nums FROM {pre}role WHERE father_id='{$id}'");
        if ($num1 && $num1['nums'] > 0)
            json_output($c, translate('ROLE_ROLE_HAS_SONROLE'));
        $num2 = $this->db->one("SELECT COUNT(*) AS nums FROM {pre}admin WHERE role_id='{$id}'");
        if ($num2 && $num2['nums'] > 0)
            json_output($c, translate('ROLE_ROLE_HAS_SONADMIN'));
        if ($this->db->delete('{pre}role', array('id' => $id))) {
            insert_log(translate('ROLE_ROLE_LOG_DEL', $id));
            $c = 1;
            $r = '';
        } else {
            $r = translate('C_TIPS_ERROR_TEXT');
        }
        json_output($c, $r);
    }

    function multi() {
        $type = $this->input->post("type");
        $ids = $this->input->post("ids");
        $c = 0;
        $r = '';
        if (count(explode(',', $ids)) == 0) {
            $r = translate('C_INVALID_PARAMS');
        } else {
            if ($type == 'delete') {
                //$this->db->query("DELETE FROM {pre}role WHERE id IN ({$ids})");
                $c = 1;
            } else {
                $r = translate('C_INVALID_PARAMS');
            }
        }
        json_output($c, $r);
    }

}